package com.hthy.futures.ui.fragment;


import android.graphics.Color;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.hthy.futures.AppConfig;
import com.hthy.futures.R;
import com.hthy.futures.api.ST_TradeApi;
import com.hthy.futures.base.BaseFragment;
import com.hthy.futures.base.CommonAdapter;
import com.hthy.futures.base.CommonViewHolder;
import com.hthy.futures.bean.Goods;
import com.hthy.futures.bean.SaveQuotePush;
import com.hthy.futures.bean.ht.BProductPriceInfo;
import com.hthy.futures.bean.ht.BRealTimeData;
import com.hthy.futures.bean.ht.BRealTimeQuotePush;
import com.hthy.futures.ui.KLineDialog;
import com.hthy.futures.ui.activity.MainActivity;
import com.hthy.futures.utils.AppOperator;
import com.hthy.futures.utils.CacheManager;
import com.hthy.futures.utils.LogUtils;
import com.hthy.futures.utils.StringUtils;
import com.vilyever.socketclient.SocketClient;
import com.wordplat.ikvstockchart.entry.EntrySet;

import net.hthy.bean.Trade;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;

/**
 * 价格
 * <p>
 * Author:  Mr.bingley
 * Version:
 * Date:  2017/3/6
 */

public class PriceFragment extends BaseFragment implements BGARefreshLayout.BGARefreshLayoutDelegate {
    @Bind(R.id.bga)
    BGARefreshLayout mRefreshLayout;
    List<BRealTimeData> mproductTradeInfos;

    public int mPosition = -1;

    @Bind(R.id.frg_price)
    LinearLayout mFragView;

    @Bind(R.id.listView)
    ListView mListView;
    private CommonAdapter<BRealTimeData> mRealTimeDataCommonAdapter;

    private List<BRealTimeData> filterBrealData = new ArrayList<>();
    private boolean isFromPricePost;
    private List<Goods> mGoodsList = new ArrayList<>();
    private KLineDialog mLineDialog;

    SaveQuotePush mSaveQuotePush = new SaveQuotePush();  // 存放历史行情list数据
    private List<BRealTimeData> mProdutInfo;

    @Override
    protected int getLayoutId() {
        return R.layout.frg_list_no_divide_height;
    }

    @Override
    protected void initWidget(View root) {
        super.initWidget(root);


        // 为BGARefreshLayout 设置代理  (必选）
        //mRefreshLayout.setDelegate(this);
        mRefreshLayout.setRefreshViewHolder(new BGANormalRefreshViewHolder(getActivity(), true));


        mRealTimeDataCommonAdapter = new CommonAdapter<BRealTimeData>(getActivity(), R.layout.adapter_price) {
            @Override
            public void convert(CommonViewHolder vh, BRealTimeData item) {
                BProductPriceInfo product_price_info = item.product_price_info;
                vh.setText(R.id.tv_good, product_price_info.ss_product_code);
                vh.setText(R.id.tv_good_code, product_price_info.ss_product_name);
                vh.setText(R.id.tv_buy_price, StringUtils.double_df.format(item.ui_open_price));
                vh.setText(R.id.tv_sell_price, StringUtils.double_df.format(item.ui_last_price));
                vh.setText(R.id.tv_most_top, StringUtils.double_df.format(item.ui_high_price));
                vh.setText(R.id.tv_most_low, StringUtils.double_df.format(item.ui_low_price));
                final int i = getDatas().indexOf(item);
                vh.getView(R.id.ll_item).setBackgroundColor(Color.WHITE);

                // 目前存在一个bug就是 当 刷新到789位置的时候，再去刷新123位置的时候 789还有之前的数据
                int colorFlg = item.colorFlg;
                switch (colorFlg) {
                    case -1:
                        ((TextView) vh.getView(R.id.tv_buy_price)).setTextColor(getResources().getColor(R.color.k_candle_common_color));
                        ((TextView) vh.getView(R.id.tv_sell_price)).setTextColor(getResources().getColor(R.color.k_candle_common_color));
                        break;
                    case 0:
                        /*((TextView)vh.getView(R.id.tv_buy_price)).setTextColor(Color.GRAY);
                        ((TextView)vh.getView(R.id.tv_sell_price)).setTextColor(Color.GRAY);*/
                        break;
                    case 1:
                        ((TextView) vh.getView(R.id.tv_buy_price)).setTextColor(Color.RED);
                        ((TextView) vh.getView(R.id.tv_sell_price)).setTextColor(Color.RED);
                        break;
                }
                // 也就是说得记住之前的位置，将其置为白色状态
                //
                List<String> history = new ArrayList<>();
                history.add(mPosition + "");

                final SocketClient socketClient = ((MainActivity) getActivity()).getSocketClient();
                vh.getView(R.id.img_k).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String ss_product_code = mRealTimeDataCommonAdapter.getDatas().get(i).product_price_info.ss_product_code;
                        String ss_product_name = mRealTimeDataCommonAdapter.getDatas().get(i).product_price_info.ss_product_name;

                        //if (mLineDialog == null) {   //得保证得new一个，不然会复用的前面的数据
                        mLineDialog = new KLineDialog(getActivity());
                        mLineDialog.setCancelable(false);
                        MainActivity.requestType = 0;
                        mLineDialog.setOnIsFirstRequest(new KLineDialog.onClickIsFirstRequest() {
                            @Override
                            public void setIsfirst(boolean isfirst) {
                                IsFirst = isfirst;
                            }
                        });
                        mLineDialog.setCanceledOnTouchOutside(true);
                        // }
                        // 把该item信息传过去。把当前的商品code传过去
                        mLineDialog.setPriceInfo(ss_product_code, ss_product_name, socketClient);
                        mLineDialog.show();
                    }
                });
            }
        };

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ((MainActivity) getActivity()).set2Fragment(position);
            }
        });

        mListView.setAdapter(mRealTimeDataCommonAdapter);

    }

    public boolean IsFirst = false;

    public boolean getIsFirst() {
        return IsFirst;
    }

    @Override
    protected void onResponse(SocketClient client, String responMes, byte[] subBytes) {
        LogUtils.e(responMes);
        mRefreshLayout.endRefreshing();
        try {
            if (isFromPricePost && responMes.indexOf("2016") != -1) {
                if (mGoodsList.size() > 0) {
                    mGoodsList.clear();
                }
                Trade.QueryProductsResponseMsg queryProductsResponseMsg = Trade.QueryProductsResponseMsg.parseFrom(subBytes);
                List<Trade.UserProductsInfo> userProductsInfoList = queryProductsResponseMsg.getUserProductsInfoList();
                for (Trade.UserProductsInfo productsInfo : userProductsInfoList) {
                    Goods goods = new Goods();
                    goods.setSs_product_code(productsInfo.getSsProductCode());
                    goods.setSs_product_name(productsInfo.getSsProductName());
                    goods.setUi_buy_pips(productsInfo.getUiBuyPips() + "");
                    goods.setUi_sell_pips(productsInfo.getUiSellPips() + "");
                    mGoodsList.add(goods);
                }

                // 筛选数据
                filterGoodsData();
                // 在这里更细就行了
                if (mRealTimeDataCommonAdapter.getDatas().size() > 0) {
                    mRealTimeDataCommonAdapter.clear();
                }
                LogUtils.e("filterBrealData", filterBrealData.size() + "");
                mRealTimeDataCommonAdapter.addItem(filterBrealData);
                mFragView.setVisibility(View.VISIBLE);

                isFromPricePost = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 这个就执行一次赋值操作。
    public void setData(List<BRealTimeData> productTradeInfos) {
        this.mProdutInfo = productTradeInfos;
        this.mproductTradeInfos = productTradeInfos;
        LogUtils.e("bbbb---pricefragment", "mProdutInfo" + mProdutInfo.size() + "---------" + mproductTradeInfos.size() + "");
        // 先获取商品种类--------------------百思不得其解为什么要放在这个位置才行。放在其它位置，点击其它页面，直接闪退了。
        // pb版本
        byte[] bytes = ST_TradeApi.searchGoods("2015");
        socketClient.sendData(bytes);

        isFromPricePost = true;


    }

    // 这个就执行一次赋值操作。
    public void refreshPriceData(List<BRealTimeData> bRealTimeDatas) {
        // 还得在这里修改价格中卖买价需要额外加上点差值  ，需要去求
        this.mproductTradeInfos = bRealTimeDatas;
        // 筛选数据
        if (mGoodsList == null) {
            return;
        }
        // 这里做的应该是 推送过来的数据和列表比较，如果是一样的话就刷星
        // filterGoodsData();
        for (int i = 0; i < filterBrealData.size(); i++) {
            BRealTimeData fiterData = filterBrealData.get(i);
            String ss_product_code = fiterData.product_price_info.ss_product_code;
            for (BRealTimeData bRealTimeData : mproductTradeInfos) {
                if (bRealTimeData.product_price_info.ss_product_code.equals(ss_product_code)) {
                    fiterData.ui_open_price = bRealTimeData.ui_last_price;   // 将其改为bRealTimeData.ui_last_price 数据都正常了，见鬼了，为啥呀，理应是……TODO
                    fiterData.ui_last_price = bRealTimeData.ui_last_price;
                    this.mPosition = i;

                    mRealTimeDataCommonAdapter.getItem(mPosition).ui_open_price = fiterData.ui_open_price;
                    mRealTimeDataCommonAdapter.notifyDataSetChanged(mListView, mPosition);
                }
            }
        }
        // 这边做的操作就是当有行情更新的时候也要进行保存
        saveSheetHistoryData();
    }

    private void filterGoodsData() {
        //
        if (filterBrealData != null && filterBrealData.size() > 0) {
            filterBrealData.clear();
        }
        LogUtils.e("bbbb", "---pricefragment--filter" + mProdutInfo.size() + "");
        if (mProdutInfo.size() == 0) {          // 有时候得到的数量是零，就通知外部重新请求下。
            // 那么去查询  刷新整个请求
            // 请求数据
            ((MainActivity) getActivity()).getOfferSheets(false);
        }
        for (Goods goods : mGoodsList) {
            for (BRealTimeData bRealTimeData : mProdutInfo) {
                if (bRealTimeData.product_price_info.ss_product_code.equals(goods.getSs_product_code())) {
                    int quote_buy_spread = Integer.parseInt(goods.getUi_buy_pips()); //8077 报价买价点差   比如10
                    int quote_sell_spread = Integer.parseInt(goods.getUi_sell_pips()); // 8078 报价卖价点差

                    bRealTimeData.quote_buy_spread = quote_buy_spread;
                    bRealTimeData.quote_sell_spread = quote_sell_spread;

                    double buyPrice = bRealTimeData.ui_open_price + quote_buy_spread;
                    double sellPrice = bRealTimeData.ui_last_price + quote_sell_spread;
                    LogUtils.e(goods.getSs_product_code() + "quote_buy_spread" + quote_buy_spread + "(" + bRealTimeData.ui_open_price + ")" + "------" +
                            "buyPrice" + buyPrice + "-------\n" +
                            "quote_sell_spread" + quote_sell_spread +
                            "sellPrice" + sellPrice);

                    bRealTimeData.ui_open_price = buyPrice;
                    bRealTimeData.ui_last_price = sellPrice;
                    bRealTimeData.product_price_info.ss_product_name = goods.getSs_product_name();


                    double temOpenPrice = bRealTimeData.ui_last_price;
                    double oldPrice = bRealTimeData.oldPrice;
                    if (oldPrice != 0) {
                        if (temOpenPrice > oldPrice) {
                            bRealTimeData.colorFlg = 1;
                        } else if (temOpenPrice == oldPrice) {
                            //mMyRelTimeDatas.get(i).colorFlg = 0;
                        } else if (temOpenPrice < oldPrice) {
                            bRealTimeData.colorFlg = -1;
                        }
                    }
                    bRealTimeData.oldPrice = temOpenPrice;

                    filterBrealData.add(bRealTimeData);
                }
            }
        }

        // 在这里保存数据最恰当
        saveSheetHistoryData();
    }

    /**
     * 缓存历史数据
     */
    private void saveSheetHistoryData() {
        mSaveQuotePush.mMyRelTimeDatas = filterBrealData;
        AppOperator.runOnThread(new Runnable() {
            @Override
            public void run() {
                CacheManager.saveObject(getActivity(), mSaveQuotePush, AppConfig.OFFETSHEET);

                SaveQuotePush saveQuotePush = (SaveQuotePush) CacheManager.readObject(getActivity(), AppConfig.OFFETSHEET);
                if (saveQuotePush != null) {
                    LogUtils.e("cache", "save" + saveQuotePush.mMyRelTimeDatas.size() + "");
                }
            }
        });
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout bgaRefreshLayout) {
        // 请求数据
        ((MainActivity) getActivity()).getOfferSheets(false);
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout bgaRefreshLayout) {
        return false;
    }

    public void setKlineDataForOne(EntrySet entrySet) {
        if (mLineDialog != null) {
            mLineDialog.setEntrySetForOne(entrySet);
        }
    }

    public void setKlineData(EntrySet entrySet) {
        if (mLineDialog != null) {
            mLineDialog.setKEntrySet(entrySet);
        }
    }

    public void setRealTimeQuotePushes(List<BRealTimeQuotePush> bRealTimeQuotePushes) {
        List<BRealTimeData> bRealTimeDatas = new ArrayList<>();
        //   接下来要把行情中的数据与报价数据进行比较，如果对应的上的话，就更新行对应的值（更新List集合中某项的值）
        mproductTradeInfos = filterBrealData;
        if (filterBrealData != null) {
            for (int i = 0; i < filterBrealData.size(); i++) {     // 遍历报价表信息
                BProductPriceInfo productInfo = filterBrealData.get(i).product_price_info;    // 得到报价表个体
                for (BRealTimeQuotePush bRealTimeQuotePush : bRealTimeQuotePushes) {
                    BProductPriceInfo product_price_info = bRealTimeQuotePush.product_price_info;

                    String ss_product_code = product_price_info.ss_product_code;
                    if (ss_product_code.equals(productInfo.ss_product_code)) {
                        filterBrealData.get(i).ui_open_price = bRealTimeQuotePush.ui_price;
                        filterBrealData.get(i).ui_last_price = bRealTimeQuotePush.ui_price;

                        // 要根据前面的值进行判断，如果是比前面的值大，则是红色的，相等则为灰色，否则为绿色的
                        double temOpenPrice = bRealTimeQuotePush.ui_price;
                        double oldPrice = filterBrealData.get(i).oldPrice;
                        if (oldPrice != 0) {
                            if (temOpenPrice > oldPrice) {
                                filterBrealData.get(i).colorFlg = 1;
                            } else if (temOpenPrice == oldPrice) {
                                //mMyRelTimeDatas.get(i).colorFlg = 0;
                            } else if (temOpenPrice < oldPrice) {
                                filterBrealData.get(i).colorFlg = -1;
                            }
                        }
                        filterBrealData.get(i).oldPrice = temOpenPrice;
                    }

                }
            }
            bRealTimeDatas.clear();
            bRealTimeDatas.addAll(filterBrealData);
            refreshPriceData(bRealTimeDatas);
        }
    }
}
